package com.lagou.demo.interceptor;

import com.lagou.demo.annotations.Security;
import com.lagou.edu.mvcframework.annotations.LagouService;
import com.lagou.edu.mvcframework.interceptor.AnnoMappedInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.List;

/**
 * @author: wudong
 * @create: 2021-06-21 17:49
 **/
@LagouService
public class SecurityAuthInterceptor implements AnnoMappedInterceptor {
    @Override
    public Annotation match(List<Annotation> pattern) {
        for (Annotation annotation : pattern) {
            if(annotation instanceof Security){
                return annotation;
            }
        }
        return null;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Annotation matchSource) throws Exception {
        Security security = (Security)matchSource;
        if(security == null){
            throw new IllegalArgumentException("认证信息Security为空");
        }
        String[] value = security.value();
        String username = request.getParameter("username");
        for (String s : value) {
            if(s.equals(username)){
                return true;
            }
        }
        throw new IllegalArgumentException(username + ",该用户没有授权");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Annotation matchSource) throws Exception {
    }
}
